

import config from 'config';
import crypto from 'crypto';
import { MysqlDataSource } from 'ROOT/db/orm';
import { User } from 'ROOT/interface/User';
import UserEntity from './user.entity';

const sign = config.get<string>('sign');

class UserService {
  private repository = MysqlDataSource.getRepository(UserEntity);

  /**
   * 查询
   * @param {object} query 
   */
  async find(query?: Partial<UserEntity>) {
    const res = await this.repository.find({ where: query })
    return res;
  }

  /**
   * 查询单个
   * @param {object} query 
   */
  async findOne(query: Partial<UserEntity>) {
    return this.repository.findOne({ where: query });
  }
  /**
   * 创建用户
   * @param {string} user 
   * @param {string} password 
   * @param {'admin' | 'user'}
   */
  async create(user: string, password: string, role?: User['role']) {
    const res = await this.repository.findOne({ where: { user } });
    if (res) {
      throw Error('用户已存在');
    }
    const pass = crypto.createHmac('md5', sign)
      .update(password)
      .digest('hex');
    const newUser = this.repository.create({ user, password: pass, role })

    return this.repository.save(newUser);
  }
}

export default new UserService();